from flask import render_template, redirect, url_for
from . import main
from flask_login import login_required, current_user
from ..models import Device, WaterQuality, PipeNetwork, MaintenanceRecord
from sqlalchemy import func
from datetime import datetime, timedelta

@main.route('/')
@main.route('/index')
@login_required
def index():
    # 获取基础统计数据
    device_count = Device.query.count()
    online_count = Device.query.filter_by(status='online').count()
    device_online_rate = online_count / device_count if device_count > 0 else 0
    
    # 获取最近的水质数据
    recent_water_data = WaterQuality.query.order_by(WaterQuality.timestamp.desc()).limit(10).all()
    normal_count = sum(1 for data in recent_water_data 
                      if 6.5 <= data.ph <= 8.5 
                      and data.turbidity <= 5.0 
                      and data.dissolved_oxygen >= 5.0)
    water_quality_normal_rate = normal_count / len(recent_water_data) if recent_water_data else 0
    
    # 获取待处理的维护记录
    pending_maintenance = MaintenanceRecord.query.filter_by(status='in_progress').count()
    
    # 获取设备状态分布
    device_status_data = [
        {'value': Device.query.filter_by(status='online').count(), 'name': '正常运行'},
        {'value': Device.query.filter_by(status='offline').count(), 'name': '离线'},
        {'value': Device.query.filter_by(status='error').count(), 'name': '故障'},
        {'value': Device.query.filter_by(status='maintenance').count(), 'name': '维护中'}
    ]
    
    # 获取最近24小时的水质数据趋势
    end_time = datetime.now()
    start_time = end_time - timedelta(hours=24)
    hourly_data = WaterQuality.query.filter(
        WaterQuality.timestamp.between(start_time, end_time)
    ).order_by(WaterQuality.timestamp).all()
    
    time_points = []
    ph_data = []
    turbidity_data = []
    oxygen_data = []
    
    if hourly_data:
        for data in hourly_data:
            time_points.append(data.timestamp.strftime('%H:%M'))
            ph_data.append(float(data.ph))
            turbidity_data.append(float(data.turbidity))
            oxygen_data.append(float(data.dissolved_oxygen))
    
    # 获取最近的告警记录
    recent_alerts = []
    offline_devices = Device.query.filter_by(status='offline').order_by(Device.last_online.desc()).limit(5).all()
    for device in offline_devices:
        recent_alerts.append({
            'timestamp': device.last_online.strftime('%Y-%m-%d %H:%M'),
            'device_name': device.name,
            'type': '设备离线',
            'status': '未处理'
        })
    
    # 获取最近的维护记录
    maintenance_records = MaintenanceRecord.query.order_by(
        MaintenanceRecord.maintenance_date.desc()
    ).limit(5).all()
    
    return render_template('index.html',
                         title='系统概览',
                         device_count=device_count,
                         water_quality_normal_rate=water_quality_normal_rate,
                         pending_maintenance=pending_maintenance,
                         device_online_rate=device_online_rate,
                         time_points=time_points,
                         ph_data=ph_data,
                         turbidity_data=turbidity_data,
                         oxygen_data=oxygen_data,
                         device_status_data=device_status_data,
                         recent_alerts=recent_alerts,
                         maintenance_records=maintenance_records) 